﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PloobsEngine.Material;
using Microsoft.Xna.Framework.Graphics;
using PloobsEngine.SceneControl;
using PloobsEngine;
using Microsoft.Xna.Framework;
using PloobsEngine.Modelo;

namespace PloobsProjectTemplate
{
    class SkyPostEffects : IPostEffect 
    {
        public List<IObject> list = new List<IObject>();

        Effect skyEffect;
        RenderTarget2D renderTarget;

        public SkyPostEffects()
            : base(PostEffectType.Deferred)
        {

        }

        public override void Init(PloobsEngine.Engine.GraphicInfo ginfo, PloobsEngine.Engine.GraphicFactory factory)
        {
            skyEffect = factory.GetEffect("SKY//skysphere_effect");
            skyEffect.Parameters["CubeMap"].SetValue(factory.GetTextureCube("SKY//Black_sky"));
            renderTarget = factory.CreateRenderTarget(ginfo.BackBufferWidth,ginfo.BackBufferHeight);
        }

        public override void Draw(Texture2D ImageToProcess, RenderHelper rHelper, GameTime gt, PloobsEngine.Engine.GraphicInfo GraphicInfo, IWorld world, bool useFloatBuffer)
        {
            rHelper.PushRenderTarget(renderTarget);
            rHelper.Clear(Color.Black);
            //skyEffect.Parameters["halfPixel"].SetValue(GraphicInfo.HalfPixel);
            //skyEffect.Parameters["DEPTH"].SetValue(rHelper[PrincipalConstants.DephRT]);
            //skyEffect.Parameters["DistortionScale"].SetValue(Distortion);
            rHelper.PushDepthStencilState(DepthStencilState.None);

            foreach (var obj in list)
            {
                IModelo modelo = obj.Modelo;

                for (int i = 0; i < modelo.MeshNumber; i++)
                {
                    BatchInformation[] bi = modelo.GetBatchInformation(i);
                    for (int j = 0; j < bi.Count(); j++)
                    {
                        Matrix w = bi[j].ModelLocalTransformation * obj.WorldMatrix;
                        skyEffect.Parameters["WorldViewProjection"].SetValue(w * world.CameraManager.ActiveCamera.View * world.CameraManager.ActiveCamera.Projection);
                        skyEffect.Parameters["WorldView"].SetValue(w * world.CameraManager.ActiveCamera.View);
                        rHelper.RenderBatch(bi[j], skyEffect);
                    }
                }
            }

            rHelper.PopDepthStencilState();
                      

            rHelper.Clear(Color.Black);
            //rHelper.RenderTextureToFullScreenSpriteBatch(ImageToProcess, effect, GraphicInfo.FullScreenRectangle);          
        }
    }
}
